(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:ApplicationCtrl
     * @description
     * # ApplicationCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('ApplicationCtrl', ["ERP_CONFIG", "$scope", "$rootScope", "$state", "dataService", "cacheService", "$timeout", "helper", "sessionService", "$location", "$window", "authService",
            function(ERP_CONFIG, $scope, $rootScope, $state, dataService, cacheService, $timeout, helper, sessionService, $location, $window, authService) {
                //初始化
                $scope.wxappid = $location.$$host.split(".")[0];
                $scope.init = function() {
                    console.error("ERP_CONFIG", ERP_CONFIG)
                    $scope.currentUser = null;
                    //初始化
                    if (!window.localStorage.lang) {
                        window.localStorage.lang = 'zh-cn';
                    }

                    $timeout(function() {
                        if (!$rootScope.currentUser) {
                            $rootScope.getUserInfo(true);
                        }
                    }, 1000);

                    doLogin();

                    if ($rootScope.logined()) {
                        wxconfig();
                    }
                }

                

                function wxconfig() {
                    dataService.jssdkSignGet($scope.wxappid, window.location.href.split("#")[0]).then(function(res) {
                        res.appId = res.app_id;
                        res.jsApiList = [
                            "addCard",
                            "launchMiniProgram"
                        ];
                        wx.config(res);
                    });
                }

                function doLogin() {
                    var urlQuery = parseLocation($window.location.search);
                    var auth_type = $location.$$search.auth_type ? true : false;

                    if (urlQuery.code) {
                        dataService.buyerWxlogin($scope.wxappid, urlQuery.code, auth_type).then(function(res) {
                            if (!res) {
                                $.alert("登录出错了！");
                            } else if (res.Msg) {
                                // console.error("aaaaa", res.Msg.indexOf("code been used"))
                                if (res.Msg.indexOf("access_token expired") || res.Msg.indexOf("code been used")) {
                                    $.alert("登录中...");
                                    $timeout(function() {
                                        goAuth2(true);
                                    }, 60000);
                                } else {
                                    $.alert(res.Msg, function() {
                                        goAuth2(true);
                                    });
                                }
                            } else {
                                //console.error("登录成功");
                                authService.loginConfirmed('success', function(config) {
                                    //自动追加token
                                    config.data["token"] = res.token;
                                    return config;
                                });

                                //清理url中的code
                                location.href = trueUrl();
                            }
                        });
                    } else {
                        $timeout(function() {
                            $rootScope.done();
                        }, 3000);
                        $scope.$on('event:auth-loginRequired', function() {
                            console.error("需要登录", $location);
                            goAuth2(true);
                        });
                    }
                }

                function goAuth2(go) {
                    // console.error($location);
                    var backUrl = encodeURIComponent(trueUrl());
                    console.error("trueUrl:", trueUrl());
                    var authType = !$location.$$search.auth_type ? "snsapi_userinfo" : "snsapi_base";
                    //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx204da65aa7d948b0&redirect_uri=http://gzh.dhfapp.com/&response_type=code&scope=snsapi_base&state=STATE&component_appid=wx9ee66f0c84c8fd71#wechat_redirect
                    var authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + $scope.wxappid + "&redirect_uri=" + backUrl + "&response_type=code&scope=" + authType + "&state=STATE&component_appid=" + ERP_CONFIG.IsvAppID;
                    console.error("authUrl:", authUrl);
                    if (go) {
                        location.href = authUrl;
                    }
                }

                function trueUrl() {
                    return $window.location.protocol + "//" + $window.location.hostname + $window.location.pathname + $window.location.hash;
                }

                //*-------------------------------------------
                // ** 全局rootScope定义 start
                // -------------------------------------------*/

                $rootScope.done = function() {
                    $timeout(function() {
                        $rootScope.initDone = true;
                    });
                }

                $rootScope.getUserInfo = function(getCache) {
                    return dataService.userCurrentGet(getCache).then(function(user) {
                        if (user) {
                            $rootScope.currentUser = $scope.currentUser = user;
                        }
                    });
                }


                function parseLocation(location) {
                    var pairs = location.substring(1).split("&");
                    var obj = {};
                    var pair;
                    var i;
                    for (i in pairs) {
                        if (pairs[i] === "")
                            continue;
                        pair = pairs[i].split("=");
                        obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
                    }
                    return obj;
                }

                //登录
                $rootScope.login = function() {
                    console.error("$rootScope.login");
                    dataService.login();
                }

                //是否已登录
                $rootScope.logined = function() {
                    return sessionService.get("token") ? true : false;
                }


                //重新登录
                $rootScope.relogin = function() {
                    $scope.currentUser = null;
                    $rootScope.login();
                }

                //注销登录
                $rootScope.logout = function() {
                    dataService.logout().then(function() {
                        $rootScope.login();
                    });
                }

                //清空缓存
                $rootScope.removeAllCache = function($event) {
                    dataService.removeDataCache();
                    window.localStorage.timezone = $scope.timezone;
                }

                //是否debug状态
                $rootScope.debug = function() {
                    return ERP_CONFIG.debug ? true : false;
                }
            }
        ]);
})();